package com.vuej.support.spring;

import com.vuej.entity.VueConfiguration;
import com.vuej.util.VueUtil;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.AbstractTemplateView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class VueView extends AbstractTemplateView {


    private VueConfiguration config;

    public VueConfiguration getConfig() {
        return config;
    }

    public void setConfig(VueConfiguration config) {
        this.config = config;
    }


    @SneakyThrows
    @Override
    protected void initServletContext(ServletContext servletContext) {
        config = BeanFactoryUtils.beanOfTypeIncludingAncestors(
                obtainApplicationContext(), VueConfiguration.class, true, false);
        config.init();
    }



    @Override
    public String getContentType() {
        return "text/html";
    }


    @Override
    protected void renderMergedTemplateModel(Map<String, Object> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        String url = getUrl();
        Assert.state(url != null, "'url' not set");

        //读取url下的.vue文件
        Resource resource = new ClassPathResource(url);
        String vue = IOUtils.toString(resource.getInputStream(),config.getVueFileCharset());


        //解析并渲染vue片段
        VueUtil.renderToString(config,vue,result -> {
            httpServletResponse.getWriter().print(result);
        });

    }
}
